package uiLayer;

import javax.swing.JPanel;

import java.awt.BorderLayout;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

import java.awt.GridLayout;

import javax.swing.border.EmptyBorder;
import javax.swing.JButton;
import javax.swing.border.TitledBorder;
import javax.swing.border.BevelBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import modelLayer.OrderLine;
import modelLayer.Product;
import controlLayer.OrderCtr;
import controlLayer.ProductCtr;

import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class SaleTab1 extends JPanel {
	private JTextField txtDate;
	private JTextField txtProductID;
	private JTextField txtProductName;
	private OrderCtr orderCtr;
	private EditableOrderLineWrapperTable orderLineTable;
	private List<OrderLineWrapper> orderLines;
	
	

	/**
	 * Create the panel.
	 * @param orderCtr 
	 */
	public SaleTab1(List<OrderLineWrapper> orderLines, OrderCtr orderCtr) {
		
		addComponentListener(new ComponentListener() {
			
			@Override
			public void componentShown(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void componentResized(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void componentMoved(ComponentEvent e) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void componentHidden(ComponentEvent e) {
				saveTab1();
			}
		});
		
		this.setOrderCtr(orderCtr);
		//orderLines = new ArrayList<OrderLineWrapper>();
		this.setOrderLines(orderLines);
		orderLineTable = new EditableOrderLineWrapperTable();
		
		setLayout(new BorderLayout(0, 0));
		
		JPanel panel = new JPanel();
		add(panel, BorderLayout.CENTER);
		panel.setLayout(new BorderLayout(0, 0));
		
		JPanel topField = new JPanel();
		topField.setBorder(new EmptyBorder(10, 10, 10, 10));
		panel.add(topField, BorderLayout.NORTH);
		topField.setLayout(new BorderLayout(0, 0));
		
		JPanel dateField = new JPanel();
		dateField.setBorder(new EmptyBorder(5, 5, 5, 5));
		topField.add(dateField, BorderLayout.EAST);
		dateField.setLayout(new BorderLayout(0, 0));
		
		txtDate = new JTextField();
		txtDate.setText("" + new Date());
		txtDate.setEditable(false);
		dateField.add(txtDate, BorderLayout.NORTH);
		txtDate.setColumns(10);
		
		
		JPanel left = new JPanel();
		left.setBorder(new TitledBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null), "S\u00F8g", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		topField.add(left, BorderLayout.CENTER);
		left.setLayout(new BorderLayout(0, 0));
		
		JPanel searchPanel = new JPanel();
		left.add(searchPanel);
		searchPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		searchPanel.setLayout(new GridLayout(0, 2, 5, 5));
		
		JLabel lblProductID = new JLabel("Varenr.:");
		searchPanel.add(lblProductID);
		
		txtProductID = new JTextField();
		txtProductID.getDocument().addDocumentListener(new DocumentListener(){

			@Override
			public void changedUpdate(DocumentEvent e) {
				adjustSearchFields();
			}

			@Override
			public void insertUpdate(DocumentEvent e) {
				adjustSearchFields();
			}

			@Override
			public void removeUpdate(DocumentEvent e) {
				adjustSearchFields();
			}
			
		});
		
		searchPanel.add(txtProductID);
		txtProductID.setColumns(10);
		
		JLabel lblProductName = new JLabel("Varenavn:");
		searchPanel.add(lblProductName);
		
		txtProductName = new JTextField();
		txtProductName.getDocument().addDocumentListener(new DocumentListener() {
			
			@Override
			public void removeUpdate(DocumentEvent e) {
				adjustSearchFields();
			}
			
			@Override
			public void insertUpdate(DocumentEvent e) {
				adjustSearchFields();
			}
			
			@Override
			public void changedUpdate(DocumentEvent e) {
				adjustSearchFields();
			}
		});
		searchPanel.add(txtProductName);
		txtProductName.setColumns(10);
		
		JLabel lblPlaceholder = new JLabel("");
		searchPanel.add(lblPlaceholder);
		
		JPanel okButtonPanel = new JPanel();
		FlowLayout flowLayout = (FlowLayout) okButtonPanel.getLayout();
		flowLayout.setAlignment(FlowLayout.RIGHT);
		left.add(okButtonPanel, BorderLayout.SOUTH);
		
		JButton btnOk = new JButton("OK");
		btnOk.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				handleClickedOK();
			}
		});
		okButtonPanel.add(btnOk);
		
		JPanel buttonPanel = new JPanel();
		panel.add(buttonPanel, BorderLayout.SOUTH);
		buttonPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5));
		
		JButton btnAnnuller = new JButton("Annuller");
		btnAnnuller.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				handleClickedCancel();
			}
		});
		buttonPanel.add(btnAnnuller);
		
		JButton btnNext = new JButton("Næste");
		btnNext.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				handleClickedNext();
			}
		});
		buttonPanel.add(btnNext);
		
		JPanel tablePanel = new JPanel();
		panel.add(tablePanel, BorderLayout.CENTER);
		tablePanel.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		tablePanel.add(scrollPane, BorderLayout.NORTH);
		scrollPane.setViewportView(orderLineTable);

	}

	protected void adjustSearchFields() {
		if (!txtProductID.getText().isEmpty()){
			txtProductName.setEditable(false);
		}
		else if (!txtProductName.getText().isEmpty()){
			txtProductID.setEditable(false);
		}
		else {
			txtProductID.setEditable(true);
			txtProductName.setEditable(true);
		}
	}

	private void handleClickedOK() {
		ProductCtr productCtr = new ProductCtr();
		
		if (!txtProductID.getText().isEmpty()){
			int id = Integer.parseInt(txtProductID.getText());
			Product product = productCtr.findProductID(id);
			OrderLine ol = null;
			//OrderLine ol = new OrderLine(1, product);
			OrderLineWrapper ow = null;
			if (product != null){
				ol = new OrderLine(1, product);
				ow = new OrderLineWrapper(ol);
				//if (ow != null){
					if (!alreadyAdded(ow, this.orderLines)){
						addOrderLine(ow);
					}
					else JOptionPane.showMessageDialog(this, "Denne vare er allerede tilføjet ordren.", "Error: 40", JOptionPane.OK_OPTION);
				//}
			}
			else JOptionPane.showMessageDialog(this, "Der er ingen vare ved id nr: " + id , "Error: Not found", JOptionPane.OK_OPTION);
		}
		if (!txtProductName.getText().isEmpty()){
			String name = txtProductName.getText();
			
			ProductDialog productDialog = new ProductDialog(productCtr, name);
			productDialog.setVisible(true);
			Product product = productDialog.getProduct();
			OrderLine ol = new OrderLine(1, product);
			OrderLineWrapper ow = new OrderLineWrapper(ol);
			if (!alreadyAdded(ow, this.orderLines)){
				addOrderLine(ow);
			}
		}
		
		resetSearchFields();
	}
	
	private boolean alreadyAdded(OrderLineWrapper ol, List<OrderLineWrapper> orderLines) {
		boolean added = false;
		for (OrderLineWrapper orderLine : orderLines){
			if (orderLine.getOrderLine().getProduct().getProductID() == ol.getOrderLine().getProduct().getProductID()){
				added = true;
			}
		}
		return added;
	}
	
	private boolean alreadyAddedOrder(OrderLine ol, List<OrderLine> orderLines) {
		boolean added = false;
		for (OrderLine orderLine : orderLines){
			if (orderLine.getProduct().getProductID() == ol.getProduct().getProductID()){
				added = true;
			}
		}
		return added;
	}

	private void resetSearchFields() {
		txtProductID.setText("");
		txtProductName.setText("");
		adjustSearchFields();
	}

	private void addOrderLine(OrderLineWrapper ow) {
		orderLines.add(ow);
		updateTable(orderLines);
	}


	private void updateTable(List<OrderLineWrapper> orderLines){
		orderLineTable.setModel(orderLines);
		
	}
	
	
	private void saveTab1() {
		List<OrderLineWrapper> ordersToSave = orderLineTable.getDataModel();
		for (OrderLineWrapper ol : ordersToSave){System.out.println("GUI: " + ol);}//DEBUG
		OrderLine ol = null;
		for (int rowIndex = 0; rowIndex < ordersToSave.size(); rowIndex++){
			ol = orderLines.get(rowIndex).getOrderLine();
			//if ((boolean) orderLineTable.getValueAt(rowIndex, 4)){
			if (ordersToSave.get(rowIndex).isAdded()){
				if (!alreadyAddedOrder(ol, orderCtr.getSalesOrder().getOrderLines())){
					orderCtr.addProduct(ol.getProduct().getProductID(), ol.getAmount());
				}
				orderCtr.updateAmount(ol.getAmount(), ol.getProduct().getProductID());
			}
			//To remove if the check box "Tilføj/Fjern" is not checked and the product earlier has been added to the salesOrder object.
			else if (alreadyAddedOrder(ol, orderCtr.getSalesOrder().getOrderLines())) {
				orderCtr.removeOrderLine(ol.getProduct().getProductID());
			}
		}
		
		for (OrderLine oll : orderCtr.getSalesOrder().getOrderLines()){System.out.println("Ctr: " + oll);}//DEBUG
		
	}

	private void handleClickedCancel() {
		orderLines.removeAll(orderLines);
		updateTable(orderLines);
	}

	/**
	 * @return the orderCtr
	 */
	public OrderCtr getOrderCtr() {
		return orderCtr;
	}

	/**
	 * @param orderCtr the orderCtr to set
	 */
	private void setOrderCtr(OrderCtr orderCtr) {
		this.orderCtr = orderCtr;
	}


	public void handleClickedNext() {
		//JTabbedPane jtp = (JTabbedPane)this.getParent();
		SaleTabbedPane saleTabbedPane = (SaleTabbedPane) this.getParent();
		saleTabbedPane.setSelectedIndex(saleTabbedPane.getSelectedIndex() + 1);
		if (orderCtr.getSalesOrder().getOrderLines().size() != 0){
			System.out.println(orderCtr.getSalesOrder().getOrderLines().size());
			//jtp.setSelectedIndex(jtp.getSelectedIndex() + 1);
			
		}
		//else JOptionPane.showMessageDialog(this, "Du skal vælge mindst en vare for at gå videre", "Error: 40", JOptionPane.OK_OPTION);
		
	}

	/**
	 * @return the orderLines
	 */
	public List<OrderLineWrapper> getOrderLines() {
		return orderLines;
	}

	/**
	 * @param orderLines the orderLines to set
	 */
	public void setOrderLines(List<OrderLineWrapper> orderLines) {
		this.orderLines = orderLines;
	}

	
	
}
